<template>
  <div>
    <div style="margin:10px 0;display: flex;flex-direction: row;justify-content:flex-end;">
      <div class="search_box">
        <el-input style="width: 400px" placeholder="请输入姓名、工号、邮箱、电话号码进行模糊查询" v-model="search" >
          <i slot="suffix" class="el-icon-close" @click="clearAndLoad"style="margin-top: 10px"></i>
        </el-input>

        <el-button class="ml-5"type="primary" @click="load">搜索</el-button>
      </div>
    </div>

    <div class="modify" style="margin: 10px 0;">
      <el-button type="primary" style="font-size: 12px; " @click="addUser">新增 <i class="el-icon-circle-plus-outline"style="margin-left:5px;"> </i></el-button>
      <el-popconfirm
          class="ml-5"
          confirm-button-text='确定'
          cancel-button-text='我再想想'
          icon="el-icon-info"
          icon-color="red"
          title="确定要删除吗？"
          @confirm="delBash"
      >
        <el-button type="danger" style="font-size: 12px;" slot="reference">批量删除<i class="el-icon-remove-outline" style="margin-left:5px;"> </i></el-button>
      </el-popconfirm>
      <el-upload action="http://localhost:9090/user/import" style="display: inline-block"
                 :show-file-list="false" accept="xlsx" :on-success="importSuccess":on-error="importFail" :headers="headersObj">
        <el-button type="primary" style="font-size: 12px; margin-left: 10px;">导入<i class="el-icon-bottom"style="margin-left:5px;"> </i></el-button>
      </el-upload>
      <el-button class="ml-5" type="primary" style="font-size: 12px; " @click="exp">导出<i class="el-icon-top"style="margin-left:5px;"> </i></el-button>
    </div>
    <!--顶部搜索筛选等操作 end-->
    <!--表格主体 start-->
    <el-table :data="tableData"
              style="width: 100%"
              :default-sort = "{prop: 'doctorId', order: 'descending'}"
              @selection-change="handleSelectionChange"
              :header-cell-style="tableHeaderColor">
      <el-table-column type="selection" width="55" ></el-table-column>
      <el-table-column prop="doctorId" label="工号"  width="80"></el-table-column>
      <el-table-column prop="doctorName" label="姓名"  width="120"></el-table-column>
      <el-table-column prop="doctorEmail" label="邮箱"  width="150"></el-table-column>
      <el-table-column prop="doctorPhoneNumber" label="电话号码"  width="150"></el-table-column>
      <el-table-column prop="departmentId" label="科号"width="120"></el-table-column>
      <el-table-column prop="roomId" label="室号"width="140"></el-table-column>
      <el-table-column prop="doctorIsAdmin" label="是否为管理员"width="100"></el-table-column>

      <el-table-column label="操作" >
        <template v-slot="scope" >
          <el-button type="success" @click.native.prevent="modifyUser(scope.$index)">编辑 <i class="el-icon-edit"></i></el-button>
          <el-popconfirm
              class="ml-5"
              confirm-button-text='确定'
              cancel-button-text='我再想想'
              icon="el-icon-info"
              icon-color="red"
              title="确定要删除吗？"
              @confirm="del(scope.$index)"
          >
            <el-button type="danger" slot="reference">删除 <i class="el-icon-remove-outline"></i></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--表格主体 end-->
    <!--分页 end-->
    <div class="pagination" >
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="pageNum"
          :page-sizes="[5,8, 10, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="count">
      </el-pagination>
    </div>
    <!--分页 end-->
    <!--嵌套表单 start-->
    <el-dialog :title="dialogFormName" :visible.sync="dialogFormVisible">
      <el-form label-width="120px" :rules="rules" ref="ruleForm" :model="form">
        <el-form-item label="姓名" prop="doctorName">
          <el-input v-model="form.doctorName" autocomplete="off" ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="doctorEmail">
          <el-input v-model="form.doctorEmail" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="doctorPhoneNumber">
          <el-input v-model="form.doctorPhoneNumber" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="科号" prop="departmentId">
          <el-input v-model="form.departmentId" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="室号"prop="roomId">
          <el-input v-model="form.roomId" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="是否为管理员"prop="doctorIsAdmin">
          <el-radio-group v-model="form.doctorIsAdmin">
<!--          <el-input v-model="form.doctorIsAdmin" autocomplete="off"></el-input>-->
            <el-radio  :label="1">是</el-radio>
            <el-radio  :label="0" >否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="saveUser">确 定</el-button>
      </div>
    </el-dialog>
    <!--嵌套表单 end-->
  </div>
</template>

<script>
export default {
  name: "User",
  data(){
    return{
      //设置页签
      plate:"系统管理",
      func:"用户管理",
      tableData: [],
      count:0,
      pageNum:1,
      pageSize:5,
      search:"",
      multipleSelection:[],
      dialogFormVisible:false,
      form:{
        doctorName:"",
        doctorEmail:"",
        doctorPhoneNumber:"",
        departmentId:"",
        roomId:"",
        doctorIsAdmin:"0"
      },
      dialogFormName:"",
      headersObj:{
        token:JSON.parse(localStorage.getItem("doctor")).token
      },
      rules:{
        doctorName:[
          {register:true,message:"医生姓名不可为空",trigger:"blur"},
          {min:2,max:15,message: "长度在 2 到 15 之间" ,trigger:"blur"},
        ],
        doctorEmail:[
          {register:true,message:"邮箱不可为空",trigger:"blur"},
          {min:8,max:255,message: "长度在 8 到 255 之间" ,trigger:"blur"}
        ],
        doctorPhoneNumber:[
          {register:true,message:"电话号码不可为空",trigger:"blur"},
          {min:11,max:11,message: "长度为 11 位" ,trigger:"blur"}
        ],
        departmentId: [
          {register:true,message:"科号不可为空",trigger:"blur"},
          {min:1,max:9,message: "长度在 1 到 9 之间",trigger:"blur"}
        ],
        roomId: [
          {register:true,message:"室号不可为空",trigger:"blur"},
          {min:1,max:9,message: "长度在 1 到 9 之间",trigger:"blur"}
        ],
        doctorIsAdmin: [
          { required: true, message: '选择是否为管理员', trigger: 'change' }
        ],
      }
    }
  },
  created() {
    //请求分页查询表格数据
    this.load();
    this.$emit("generateTab",this.plate,this.func)
  },
  methods:{
    // 修改table header的背景色
    tableHeaderColor({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return 'background-color: #e0f6fe;color: #303133;font-weight: 600;font-size:12px;'
      }
    },
    load() {
      //axios方式http://localhost:9090前缀写在了request.js文件中，可省略
      this.request.get("doctor/page",{
        params: {
          pageNum:this.pageNum,
          pageSize:this.pageSize,
          search:this.search,
        }
      }).then(res=>{
        console.log(res)
        this.tableData = res.records;
        this.count = res.total;
      })
    },
    //分页
    handleSizeChange(pageSize){
      console.log("pageSize:"+pageSize);
      this.pageSize=pageSize;
      this.load();
    },
    handleCurrentChange(pageNum){
      console.log("pageNum:"+pageNum);
      this.pageNum=pageNum;
      this.load();
    },
    clearAndLoad(){
      this.pageNum=1;
      this.pageSize=5;
      this.search="";
      this.load();
    },
    //点击新增用户弹窗
    addUser(){
      this.form={
        doctorName:"",
        doctorEmail:"",
        doctorPhoneNumber:"",
        departmentId:"",
        roomId:"",
        doctorIsAdmin:"0"
      }
      console.log(this.from)
      this.dialogFormName="【新增用户】"
      this.dialogFormVisible=true;
    },
    //点击确认保存或更新用户信息
    saveUser(){
      console.log(this.form.doctorName)
      // if(this.form.username==""||this.form.password==""||this.form.nickname==""||
      // this.form.phone==""||this.form.campus==""||this.form.area==""||this.form.building==""||this.form.dormitory==""){
      //   this.$message.error("用户信息不能为空！")
      //   console.log("用户信息不能为空！")
      //   return false
      // }
      //校验账号和密码长度以及电话号码
      // if(this.form.username.length<3||this.form.username.length>15){
      //   this.$message.error("用户名长度应在3-15范围内！")
      //   console.log("用户名长度应在3-15范围内！")
      //   return false
      // }
      // if(this.form.password.length<3||this.form.password.length>15){
      //   this.$message.error("密码长度应在3-15范围内！")
      //   console.log("密码长度应在3-15范围内！")
      //   return false
      // }
      // if(this.form.phone.length<11||this.form.phone.length>13){
      //   this.$message.error("电话号码长度应在11-13范围内！")
      //   console.log("电话号码长度应在3-15范围内！")
      //   return false
      // }
      if(/^1[3456789]\d{9}$/.test(this.form.doctorPhoneNumber) == false){
        this.$message.warning("手机号码格式错误，请输入正确的电话号码!");
        return false;
      }
        //工号和密码初始为一样
        this.dialogFormVisible = false;
        this.request.post("/doctor/save", this.form).then(res => {
          console.log(res)
          if (res.code == "200") {
            this.$message.success("保存成功！");
            this.load();
          } else {
            this.$message.error(res.msg);
          }
        })
    },
    //用户点击取消
    cancel(){
      this.dialogFormVisible=false;
      this.load();
    },
    //点击编辑用户
    modifyUser(idx){
      //console.log("tableData:",this.tableData);
      //console.log("index:"+idx)
      //console.log("row:"+res)
      this.dialogFormName="【编辑用户】"
      let res=this.tableData[idx];
      this.dialogFormVisible=true;
      delete res.newid;
      this.form=res;
    },
    //点击删除用户
    del(idx){
      let doctorId=this.tableData[idx].doctorId;
      console.log("doctorId:"+doctorId)
      this.request.delete("/doctor?doctorId="+doctorId).then(res=>{
        console.log(res)
        if(res){
          this.$message.success("删除成功！");
          this.load();
        }else{
          this.$message.error("删除失败！");
        }
      })
    },
    //批量删除用户——选择
    handleSelectionChange(val){
      console.log(val)
      this.multipleSelection = val;
    },
    //点击批量删除按钮
    delBash(){
      console.log("点击批量删除按钮")
      let ids=this.multipleSelection.map(v=>v.doctorId)
      console.log(ids)
      this.request.post("/doctor/del/bash",ids).then(res=>{
        console.log(res)
        if(res){
          this.$message.success("删除成功！");
          this.load();
        }else{
          this.$message.error("删除失败！");
        }
      })
    },
    //导出
    exp(){
      //无用户信息（token）则代表当前为非法登录，不能够使用导出接口
      let doctor=localStorage.getItem("doctor")
      //console.log(user)
      if (doctor==null){
        this.$message("无用户信息，请重新登录！")
        return false
      }else{
        var token=JSON.parse(doctor).token
        if(token==null){
          this.$message("无token信息，请重新登录！")
          return false
        }
      }
      //导出不拦截，在前端请求时，另外请求一个没有任何用处的token方法，达到校验的目的
      this.request.post("/doctor/token").then(res=> {
        console.log("res:" + res);
        if (res.code === '401') {
          return false
        } else {
          window.open("http://localhost:9090/doctor/export")
          return true
        }
      })
    },
    //导入前的检查
    //导入
    //导入成功
    importSuccess(){
      this.request.post("/doctor/token").then(res=> {
        console.log("res:" + res);
        if (res.code === '401') {
          this.$message.error("导入失败！");
          this.load();
        } else {
          this.$message.success("导入成功！");
          this.load();
        }
      })
    },
    //导入失败
    importFail(){
      this.$message.error("导入失败！");
      this.load();
    },
  }
}
</script>

<style>
.el-menu {
  height: 100%;
  border-right-width: 0;
}
.pagination,.search_box{
  padding: 10px 0px;
}
</style>